package de.snom;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class LoginDataDialog extends Dialog {

	private static final String USER_CONFIG = "/.user.config";
	private static final String GOOGLE_USER_NAME = "GoogleUserName=";
	private static final String PHONE_USER_NAME = "PhoneUserName=";
	private static final String PHONE_URL = "PhoneURL=";
	private static final String PHONE_PASSWORD = "PhonePassword=";
	private static String USER_CONFIG_PATH = "";
	protected Object result;
	protected Shell shell;
	private Text usernameField;
	private Text passwordField;
	private String username = "";
	private Label lblPhonePassword;
	private Text phonePassword;
	private Label lblPhoneUsername;
	private Text phoneUser;
	private Label lblPhoneurl;
	private Text phoneUrl;


	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public LoginDataDialog(Shell parent, int style) {
		super(parent, style);
		String osName = System.getProperty("os.name").toLowerCase();
		if (osName.indexOf("windows") != -1) {

			System.out.println("IRGENDEINE Windows Variante");
			USER_CONFIG_PATH = System.getProperty("user.home")
					+ "/AppData/Local/snom";

		} else if (osName.indexOf("mac os x") != -1) {
			System.out.println("Mac");
			USER_CONFIG_PATH = System.getProperty("user.home")
					+ "/Library/snom";
		} else {
			USER_CONFIG_PATH = System.getProperty("user.home")
					+ "/.config/snom";
		}
		setText("Logindata");
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		readConfig();
		createContents();
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		Monitor primary = display.getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = shell.getBounds();

		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;

		shell.setLocation(x, y);
		
		lblPhonePassword = new Label(shell, SWT.NONE);
		lblPhonePassword.setText("Phone Password");
		lblPhonePassword.setBounds(51, 89, 120, 19);
		
		lblPhoneUsername = new Label(shell, SWT.NONE);
		lblPhoneUsername.setText("Phone UserName");
		lblPhoneUsername.setBounds(51, 64, 120, 19);
		
		lblPhoneurl = new Label(shell, SWT.NONE);
		lblPhoneurl.setText("Phone URL");
		lblPhoneurl.setBounds(51, 39, 120, 19);
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}

		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), getStyle());
		shell.setSize(340, 190);
		shell.setText(getText());
		
		phoneUrl = new Text(shell, SWT.BORDER);
		phoneUrl.setText(PhoneData.get().getPhoneURLString());
		phoneUrl.setBounds(195, 36, 135, 19);
		
		phoneUser = new Text(shell, SWT.BORDER);
		phoneUser.setText(PhoneData.get().getPhoneUserNameString());
		phoneUser.setBounds(195, 61, 135, 19);
		
		phonePassword = new Text(shell, SWT.BORDER | SWT.PASSWORD);
		phonePassword.setText(PhoneData.get().getPhonePasswordString());
		phonePassword.setBounds(195, 86, 135, 19);

		usernameField = new Text(shell, SWT.BORDER);
		usernameField.setText(username);
		usernameField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.keyCode == 13) {
					LoginDataDialog.this.close();
				}
			}
		});
		usernameField.setBounds(195, 114, 135, 19);

		passwordField = new Text(shell, SWT.BORDER | SWT.PASSWORD);
		passwordField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if (e.keyCode == 13) {
					LoginDataDialog.this.close();
				}
			}
		});
		passwordField.setBounds(195, 139, 135, 19);
		if (!"".equals(username)) {
			passwordField.setFocus();
		}
		Label lblPassword = new Label(shell, SWT.NONE);
		lblPassword.setBounds(51, 142, 120, 14);
		lblPassword.setText("Password");

		Label lblMailadress = new Label(shell, SWT.NONE);
		lblMailadress.setText("Mailadress");
		lblMailadress.setBounds(51, 117, 120, 19);

	}

	protected void close() {
		this.username = this.usernameField.getText();
		PhoneData.get().setPhonePasswordString(this.phonePassword.getText());
		PhoneData.get().setPhoneURLString( this.phoneUrl.getText());
		PhoneData.get().setPhoneUserNameString(this.phoneUser.getText());
		AdressBook.get().setUsername(this.username);
		AdressBook.get().setPassword(this.passwordField.getText());
	
		if (AdressBook.get().updateAdressBook()) {
			writeConfig();
			shell.close();
		}else {
			ErrorDialog.openError(shell,  "login failed", "login failed", new Status(IStatus.ERROR, "My Plug-in ID", 0,
		            "Maybe you entered something wrong - Dude", null)) ;
		}
	}

	private void readConfig() {
		ArrayList<String> read = new ArrayList<String>();
		BufferedReader in = null;
		try {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(
					USER_CONFIG_PATH + USER_CONFIG)));
			String s;
			while (null != (s = in.readLine())) {
				read.add(s);
				if (s.startsWith(GOOGLE_USER_NAME)) {
					this.username = s.substring(GOOGLE_USER_NAME.length());
				}else if (s.startsWith(PHONE_USER_NAME)) {
					PhoneData.get().setPhoneUserNameString( s.substring(PHONE_USER_NAME.length()));
				}else if (s.startsWith(PHONE_URL)) {
					PhoneData.get().setPhoneURLString( s.substring(PHONE_URL.length()));
				}else if (s.startsWith(PHONE_PASSWORD)) {
					PhoneData.get().setPhonePasswordString(s.substring(PHONE_USER_NAME.length()));
				}
			}
		} catch (FileNotFoundException ex) {
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	private void writeConfig() {
		BufferedWriter out = null;
		try {
			System.out.println(USER_CONFIG);
			File file = new File(USER_CONFIG_PATH);
			file.mkdirs();
			out = new BufferedWriter(new OutputStreamWriter(
					new FileOutputStream(USER_CONFIG_PATH + USER_CONFIG)));
			out.write(GOOGLE_USER_NAME + username);
			out.write("\n");
			out.write(PHONE_PASSWORD+PhoneData.get().getPhonePasswordString());
			out.write("\n");
			out.write(PHONE_URL + PhoneData.get().getPhoneURLString());
			out.write("\n");
			out.write(PHONE_USER_NAME+PhoneData.get().getPhoneUserNameString());
			out.write("\n");
			System.out.println(file.getAbsolutePath());
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}

	}

}
